package cn.edu.stu.syllabus.datas;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.edu.stu.syllabus.repository.takeout.local.DishesEntry;

/**
 * Created by daidaijie on 2017/4/12.
 */

public class TakeOutBuyMap {

    private static volatile Map<String, Map<DishesEntry, Integer>> mTakeOutAllBuyMap;

    public static Map<String, Map<DishesEntry, Integer>> getInstance() {
        if (mTakeOutAllBuyMap == null) {
            synchronized (TakeOutBuyMap.class) {
                if (mTakeOutAllBuyMap == null) {
                    mTakeOutAllBuyMap = new HashMap<>();
                }
            }
        }
        return mTakeOutAllBuyMap;
    }

    public static void setInstance(Map<String, Map<DishesEntry, Integer>> takeOutAllBuyMap) {
        mTakeOutAllBuyMap = takeOutAllBuyMap;
    }

    public static Map<DishesEntry, Integer> getTakeOutBuyMap(String objectId) {
        Map<DishesEntry, Integer> buymaps = getInstance().get(objectId);
        if (buymaps == null) {
            buymaps = new LinkedHashMap<>();
            getInstance().put(objectId, buymaps);
        }
        return buymaps;
    }

    public static List<DishesEntry> getTakeOutBuyMapList(String objectId) {
        List<DishesEntry> dishesEntries = new ArrayList<>();

        Map<DishesEntry, Integer> buymaps = getTakeOutBuyMap(objectId);
        Iterator<Map.Entry<DishesEntry, Integer>> iterator = buymaps.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<DishesEntry, Integer> entry = iterator.next();
            DishesEntry dishesEntry = entry.getKey();
            dishesEntries.add(dishesEntry);
        }
        return dishesEntries;
    }

    public static MenuCounterHolder getMenuCount(String objectId) {
        Map<DishesEntry, Integer> buymaps = getTakeOutBuyMap(objectId);
        Iterator<Map.Entry<DishesEntry, Integer>> iterator = buymaps.entrySet().iterator();
        MenuCounterHolder menuCounterHolder = new MenuCounterHolder();
        while (iterator.hasNext()) {
            Map.Entry<DishesEntry, Integer> entry = iterator.next();
            DishesEntry dishesEntry = entry.getKey();
            int num = entry.getValue();
            if (dishesEntry.isCalcable()) {
                menuCounterHolder.sumPrice += dishesEntry.getPriceDouble() * num;
            } else {
                menuCounterHolder.uncalcableNum += num;
            }
            menuCounterHolder.sumNum += num;
        }
        return menuCounterHolder;
    }

    public static void clear() {
        if (mTakeOutAllBuyMap != null) {
            mTakeOutAllBuyMap.clear();
        }
        mTakeOutAllBuyMap = null;
    }

}
